package com.ruoyi.web.controller.system;
import com.fasterxml.jackson.databind.JsonNode;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.domain.GwRouter;
import com.ruoyi.system.domain.vo.IdentityQueryVo;
import com.ruoyi.system.service.IGwHomeSummarizeService;
import com.ruoyi.system.service.IGwRouterService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.utils.RedisRateLimiterWithBlacklistWhitelist;
import com.ruoyi.web.controller.tool.EncryptionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;

/**
 * 标识查询Controller
 *
 * @author ruoyi
 * @date 2024-11-10
 */
@RestController
@RequestMapping("/system/identityQuery")
@Api(tags = "标识查询")
public class GwIdentityQueryController  extends BaseController {


    @Autowired
    private IGwRouterService gwRouterService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private  RestTemplate restTemplate;
    @Autowired
    private IGwHomeSummarizeService gwHomeSummarizeService;
    @Autowired
    private RedisRateLimiterWithBlacklistWhitelist limiterWithBlacklistWhitelist;

    @Autowired
    private EncryptionUtil EncryptionUtilService;
    @Value("${ase.key}")
    private     String key;
    /**
     * 标识查询
     */
//    @GetMapping(value = "/code/{version}/{identifier}")
//    @ApiOperation(value = "标识查询", notes = "标识查询")
//    public AjaxResult getCodeInfo(@PathVariable("version") String version
//            , @PathVariable("identifier") String identifier, HttpServletRequest request) throws Exception {
//        String code=version+"/"+identifier;
//
//        //检测ip,防爬ip，对爬虫ip进行封禁
//        String ip = IpUtils.getIpAddr(request);
//        //检测ip是否允许查询
//        if (!limiterWithBlacklistWhitelist.isAllowed(ip)){
//            return AjaxResult.error("ip被封禁");
//        }
//
//
//        // gwIdentityQueryService.pattern(code);
//        // 示例输入: "2.4108.789110/11AABBCC-ABCDEFG"
//        System.out.println(code);
//        String pattern = "^\\d\\.\\d{4}\\.\\d+/[A-Za-z0-9]+-[A-Za-z0-9]+$";
//        if (!code.matches(pattern)) {
//            return AjaxResult.error("标识格式错误，请检查输入标识");
//        }
//
//        String[] parts = code.split("\\.");
//        if (parts.length < 3) {
//            return AjaxResult.error("输入格式错误，请检查输入标识。");
//        }
//
//        // 找到第二个 . 的位置
//        int secondDotIndex = code.indexOf('.', code.indexOf('.') + 1);
//        String nodeIdentifier = code.substring(0, secondDotIndex);
//
//        System.out.println(nodeIdentifier);  // 输出：2.4108
//        // 找到第二个 . 和 / 的位置
//        int threeDotIndex = code.indexOf('.', code.indexOf('.') + 1);
//        int slashIndex = code.indexOf('/');
//        String prefix ="";
//        // 确保找到第二个 . 和 /
//        prefix = code.substring(threeDotIndex + 1, slashIndex);
//        System.out.println(prefix);  // 输出：1000
//
//        GwRouter gwRouter = gwRouterService.selectGwRouterByNodeIdentifierAndPrefix(nodeIdentifier,prefix);
//        String response="";
//
//        // 创建 ObjectMapper 实例
//        ObjectMapper objectMapper = new ObjectMapper();
//
//
//        //当前节点没有数据向上查找
//        if(gwRouter==null) {
//            return error("数据不存在");
//
//       //外部企业
//        }else if ("1".equals(gwRouter.getInOutStatus())){
//            // 定义目标 URL
//            String url = gwRouter.getDomain()+"/html/code/"+code;
//            // 发送 GET 请求并获取响应体
//            response = restTemplate.getForObject(url, String.class);
//
//            // 输出响应内容
//
//
//            // 首先将整个 JSON 解析为树结构
//            JsonNode rootNode = objectMapper.readTree(response);
//
//            // 提取 data 字段的 JSON 字符串内容
//            String dataString = rootNode.get("data").asText();
//
//            // 将 data 字符串反序列化为 DataVo 对象
//
//            // String decrypt = AESUtil.encrypt(dataString, key);
//            return AjaxResult.success("查询成功！",dataString);
//
//        }else {
//            IdentityQueryVo identityQueryVo = new IdentityQueryVo();
//            SysDept sysDept = deptService.selectGwRouterByNodeIdentifier(nodeIdentifier);
//            // 定义目标 URL
//            String url = sysDept.getDomain()+"/html/code/"+code;
//            // 发送 GET 请求并获取响应体
//            response = restTemplate.getForObject(url, String.class);
//            // 输出响应内容
//            // 首先将整个 JSON 解析为树结构
//            JsonNode rootNode = objectMapper.readTree(response);
//            // 提取 data 字段的 JSON 字符串内容
//            String dataString = rootNode.get("data").asText();
//
//
//           // String decrypt = AESUtil.encrypt(dataString, key);
//            return AjaxResult.success("查询成功！",dataString);
//        }
//
//    }

    @GetMapping(value = "/code/{version}/{identifier}")
    @ApiOperation(value = "标识查询", notes = "标识查询")
    public AjaxResult getCodeInfo(@PathVariable("version") String version,
                                  @PathVariable("identifier") String identifier,
                                  HttpServletRequest request) throws Exception {
        String code = version + "/" + identifier;
        String ip = IpUtils.getIpAddr(request);

        // 检测 IP 是否允许查询
        if (!limiterWithBlacklistWhitelist.isAllowed(ip)) {
            return AjaxResult.error("IP 被封禁");
        }

        // 校验标识格式
        if (!code.matches(REGEX_PATTERN)) {
            return AjaxResult.error("标识格式错误，请检查输入标识");
        }

        // 解析 nodeIdentifier 和 prefix
        String nodeIdentifier = extractNodeIdentifier(code);
        String prefix = extractPrefix(code);
        if (nodeIdentifier == null || prefix == null) {
            return AjaxResult.error("输入格式错误，请检查输入标识。");
        }

        GwRouter gwRouter = gwRouterService.selectGwRouterByNodeIdentifierAndPrefix(nodeIdentifier, prefix);
        if (gwRouter == null) {
            return AjaxResult.error("数据不存在");
        }

        String response = fetchExternalData(gwRouter, nodeIdentifier, code);
        if (response == null) {
            return AjaxResult.error("数据获取失败");
        }

        return AjaxResult.success("查询成功！", extractData(response));
    }

    /**
     * 正则表达式校验规则
     */
    private static final String REGEX_PATTERN = "^\\d\\.\\d{4}\\.\\d+/[A-Za-z0-9]+-[A-Za-z0-9]+$";

    /**
     * 提取 nodeIdentifier
     */
    private String extractNodeIdentifier(String code) {
        int secondDotIndex = code.indexOf('.', code.indexOf('.') + 1);
        return secondDotIndex != -1 ? code.substring(0, secondDotIndex) : null;
    }

    /**
     * 提取 prefix
     */
    private String extractPrefix(String code) {
        int secondDotIndex = code.indexOf('.', code.indexOf('.') + 1);
        int slashIndex = code.indexOf('/');
        return (secondDotIndex != -1 && slashIndex != -1) ? code.substring(secondDotIndex + 1, slashIndex) : null;
    }

    /**
     * 获取外部数据
     */
    private String fetchExternalData(GwRouter gwRouter, String nodeIdentifier, String code) {
        String url;
        if ("1".equals(gwRouter.getInOutStatus())) {
            url = gwRouter.getDomain() + "/html/code/" + code;
        } else {
            SysDept sysDept = deptService.selectGwRouterByNodeIdentifier(nodeIdentifier);
            url = sysDept.getDomain() + "/html/code/" + code;
        }

        try {
            return restTemplate.getForObject(url, String.class);
        } catch (Exception e) {

            return null;
        }
    }

    /**
     * 解析 JSON 数据
     */
    private String extractData(String response) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(response);
            return rootNode.get("data").asText();
        } catch (Exception e) {

            return null;
        }
    }

    @PreAuthorize("@ss.hasPermi('system:router:query')")
    @GetMapping(value = "/")
    public AjaxResult getCodeInfo1()
    {
        String code ="2.4108.123456/11AADD5-1V3J2423SK";
        // 示例输入: "2.4108.789110/11AABBCC-ABCDEFG"
        String pattern = "^\\d\\.\\d{4}\\.\\d+/[A-Za-z0-9]+-[A-Za-z0-9]+$";
        if (!code.matches(pattern)) {
            return AjaxResult.error("标识格式错误，请检查输入标识");
        }

        String[] parts = code.split("\\.");
        if (parts.length < 3) {
            return AjaxResult.error("输入格式错误，请检查输入标识。");
        }

        // 找到第二个 . 的位置
        int secondDotIndex = code.indexOf('.', code.indexOf('.') + 1);
        String nodeIdentifier = code.substring(0, secondDotIndex);

        System.out.println(nodeIdentifier);  // 输出：2.4108
        // 找到第二个 . 和 / 的位置
        int threeDotIndex = code.indexOf('.', code.indexOf('.') + 1);
        int slashIndex = code.indexOf('/');
        String prefix ="";
        // 确保找到第二个 . 和 /
        prefix = code.substring(threeDotIndex + 1, slashIndex);
        System.out.println(prefix);  // 输出：1000

        GwRouter gwRouter = gwRouterService.selectGwRouterByNodeIdentifierAndPrefix(nodeIdentifier,prefix);

        if (gwRouter!=null){
            deptService.selectGwRouterByNodeIdentifier(nodeIdentifier);

        }

        return success();
    }


}
